package com.boy.service.impl;


import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.boy.base.Setting;
import com.boy.commonutils.handler.WhdException;
import com.boy.service.FileService;
import com.boy.tool.enumClass.ExceptionCode;
import io.minio.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Slf4j
@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private Setting minIOConfigProperties;

    private final static String separator = "/"; //文件夹分隔符


    /**
     * 构建文件的绝对路径
     *
     * @param dirPath  文件路径
     * @param filename 文件名  yyyy/mm/dd/file.jpg
     * @return /test
     */
    public String builderFilePath(String dirPath, String filename) {
        StringBuilder stringBuilder = new StringBuilder(50);
        if (!StringUtils.isEmpty(dirPath)) {
            stringBuilder.append(dirPath).append(separator);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        String todayStr = sdf.format(new Date());
        stringBuilder.append(todayStr).append(separator);
        stringBuilder.append(filename);
        return stringBuilder.toString();
    }

    @Override
    public String uploadFile(MultipartFile file) {
        // 获取文件名称
        String fileName = file.getOriginalFilename();
        int lastDot = fileName.lastIndexOf(".");
        String ext = fileName.substring(lastDot);
        String newName = UUID.randomUUID().toString().replace("-", "") + ext;
        StringBuilder urlPath = new StringBuilder(minIOConfigProperties.getEndpoint());
        String filePath = builderFilePath("", newName);
        try {
            // 获取文件输入流
            InputStream is = file.getInputStream();
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .object(filePath) //文件名
                    .contentType(file.getContentType())//文件类型
                    .bucket(minIOConfigProperties.getBucket())//桶名称与minio创建的桶一致
                    .stream(is, is.available(), -1)//文件流
                    .build();
            minioClient.putObject(putObjectArgs);
            urlPath.append(separator).append(minIOConfigProperties.getBucket());
            urlPath.append(separator);
            urlPath.append(filePath);
            return urlPath.toString();
        } catch (Exception ex) {
            log.error("minio put file error.", ex);
            ex.printStackTrace();
            throw new WhdException(ExceptionCode.SYSTEM_RUN_EXCEPTION, "上传文件失败");
        }
    }

}